<template>
    <el-card class="card f fv">
        <div class="f fac fpj">
            <div class="title">农场列表</div>
            <div class="operation">
                <el-button type="primary" @click="openDialog(null, '添加')">添加农场</el-button>
            </div>
        </div>
        <!-- 搜索条件 -->
        <el-form style="margin-top: 0.12rem;" :model="data.searchform" :inline="true">
            <el-form-item label="农场类型">
                <el-select style="width: 2rem;" clearable @change="getList(true)" v-model="data.searchform.type"
                    placeholder="请选择农场类型">
                    <el-option label="种植" :value="1" />
                    <el-option label="养殖" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="名称">
                <el-input clearable style="width: 2rem;" @clear="getList(true)" v-model="data.searchform.name"
                    placeholder="请输入农场名称" />
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="getList(true)">搜索</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="data.tableList" :height="data.tableHeight" v-loading="data.tableLoading" stripe class="table">
            <el-table-column prop="name" align="center" label="名称" />
            <el-table-column prop="location" align="center" label="位置" />
            <el-table-column prop="area" align="center" label="面积" />
            <el-table-column prop="type" align="center" label="类型">
                <template #default="scope">
                    <span>{{ scope.row.type == 1 ? '种植' : '养殖' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="create_time" align="center" label="创建时间">
                <template #default="scope">
                    <span>{{ scope.row.create_time && utils.formatDate(new Date(scope.row.create_time).getTime(), 'Y-M-D H:I:S') }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template #default="scope">
                    <span class="table-edit" @click="openDialog(scope.row, '编辑')">编辑</span>
                    <span class="table-delete" @click="deleteLand(scope.row)">删除</span>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background style="margin-top: 0.16rem;" layout="->, total, sizes, prev, pager, next" :pager-count="5"
            v-model:current-page="data.pageNum" v-model:page-size="data.pageSize" :total="data.total"
            @size-change="getList()" @current-change="getList()" />

        <!-- 抽屉/弹框 -->
        <el-drawer v-model="dialogData.dialogVisible" :title="dialogData.dialogTitle" direction="rtl" @close="closeDialog">
            <div class="content">
                <el-form :model="dialogData.form" label-postion="left" label-width="0.8rem" :rules="dialogData.formRules" hide-required-asterisk ref="refForm">
                    <el-form-item label="农场名称" prop="name">
                        <el-input v-model="dialogData.form.name" placeholder="请输入农场名称" />
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="14">
                            <el-form-item label="位置" prop="location">
                                <el-input disabled v-model="dialogData.form.location" placeholder="添加区域后获取位置" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="面积" prop="location">
                                <el-input disabled v-model="dialogData.form.area" placeholder="请获取面积" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="" prop="">
                        <div class="map">
                            <Map v-if="dialogData.dialogVisible" :landInfo="dialogData.form" @setCenterArea="setCenterArea"></Map>
                        </div>
                    </el-form-item>
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="dialogData.form.type" placeholder="请选择农场类型">
                            <el-option label="种植" :value="1" />     
                            <el-option label="养殖" :value="2" />                                  
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="footer">
                    <el-button type="primary" @click="submit">确定</el-button>
                    <el-button @click="closeDialog">取消</el-button>
                </div>
            </div>
        </el-drawer>
    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive, watchEffect } from 'vue'
import http from '@/api/home'
import utils from '@/utils/utils'
import Map from "@/components/Map.vue"

const refForm = ref()

// 数据集
const data = reactive({
    // 搜索表单对象
    searchform: {},
    // 表格数据
    tableList: [],
    // 表格高度
    tableHeight: 0,
    // 表格加载
    tableLoading: false,
    // 分页 
    pageNum: 1,
    pageSize: 20,
    total: 0,
})

// 弹框
const dialogData = reactive({
    // 是否显示
    dialogVisible: false,
    // 标题
    dialogTitle: '',
    // 表单数据 
    form: {},
    // 校验规则
    formRules: {
        name: [{ required: true, message: '请输入农场名称', trigger: 'blur' }],
        location: [{ required: true, message: '请选择位置', trigger: 'blur' }],
        area: [{ required: true, message: '请选择面积', trigger: 'blur' }],
        type: [{ required: true, message: '请选择农场类型', trigger: 'change' }],
    },
})

onMounted(() => {
    getList()
})

// 获取列表
const getList = (reset = false) => {
    if (reset) data.pageNum = 1
    data.tableLoading = true
    http.landList({
        ...data.searchform,
        pageNum: data.pageNum,
        pageSize: data.pageSize
    }).then(res => {
        data.tableLoading = false
        data.tableList = res.data.records
        data.total = res.data.total
    }).finally(() => {
        data.tableLoading = false
    })
}

// 打开对话框
const openDialog = (row, title) => {
    dialogData.dialogVisible = true
    if (row) {
        dialogData.form = { ...row }
    } else {
        dialogData.form = {}
    }
    dialogData.dialogTitle = title
}

// 关闭对话框
const closeDialog = () => {
    dialogData.dialogVisible = false;
    refForm.value.resetFields();
    dialogData.form = {}
}

// 传给子组件获取面积和位置的方法
const setCenterArea = (val) => {
    console.log("父组件接受到了数据：", val);
    if (val.location) {
        let lnglat = val.location.split(',')
        dialogData.form.location = parseFloat(lnglat[0]).toFixed(7) + ',' + parseFloat(lnglat[1]).toFixed(7)
    } else {
        dialogData.form.location = ''
    }
    dialogData.form.area = val.area ? parseFloat(val.area).toFixed(2) : ''
    dialogData.form.geojson = val.geojson ? val.geojson : ''
}

//提交
const submit = () => {
    refForm.value.validate((valid) => {
        if (valid) {
            if (dialogData.dialogTitle == '添加') {
                http.landAdd(dialogData.form).then(res => {
                    ElMessage({ type: 'success', message: res.message })
                    dialogData.dialogVisible = false
                    getList()
                })
            } else {
                http.landUpdate(dialogData.form).then(res => {
                    ElMessage({ type: 'success', message: res.message })
                    dialogData.dialogVisible = false
                    getList()
                })
            }
        }
    })
}

// 删除
const deleteLand = (data) => {
    ElMessageBox.confirm(
        '是否删除该农场?',
        '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }
    ).then(() => {
        http.landDelete({ id: data.id }).then(res => {
            ElMessage({ type: 'success', message: res.message })
            getList()
        })
    })
}

// 设置表格高度
const setTableHeight = () => {
    let tableH = 320 // 距离下方的距离 
    let tableHeightDetail = window.innerHeight - tableH
    if (tableHeightDetail <= 400) {
        data.tableHeight = 400
    } else {
        data.tableHeight = window.innerHeight - tableH
    }
}
watchEffect(() => setTableHeight())

</script>

<style lang="scss" scoped>
.card {
    box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
    margin-top: 0.14rem;
    height: calc(100vh - 0.68rem - 0.7rem);

    .title {
        font-size: 0.2rem;
        font-weight: bold;
        color: #000;
        padding-bottom: 0.1rem;
        border-bottom: 4px solid $ncpColor;
    }

    .role-input {
        width: 2rem;
        margin-right: 0.2rem;
    }

    .table {
        width: 100%;

        .table-sale {
            color: $helpColor;
        }

        .table-info {
            color: #9CA3AF;
            font-size: 0.12rem;
        }
    }

    .table-edit {
        color: $otherColor;
        margin-right: 0.2rem;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    .disabled {
        pointer-events: none;
        opacity: 0.8;
    }

    .table-delete {
        color: $helpColor;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    :deep(.el-drawer__title) {
        font-size: 0.16rem;
    }

    .content {
        position: relative;
        height: 100%;
        .map {
            width: 100%;
            height: 5.6rem;
        }

        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
        }
    }

}</style>